using System;
using System.IO;
using System.Xml.Serialization;
using Koonfusion.SyncDeploy.Core.Manifest;

namespace Koonfusion.SyncDeploy.Core.Services
{
    public class ManifestService
    {
        internal readonly XmlSerializer _xmlSerializer = new XmlSerializer(typeof(SyncManifest), "http://syncdeploy.googlecode.com/syncdefinition");

        internal  SyncManifest Read(String manifest)
        {
            var stringReader = new StringReader(manifest);
            return (SyncManifest)_xmlSerializer.Deserialize(stringReader);
        }

        internal SyncManifest Read(FileInfo manifestFile)
        {

            return Read(File.ReadAllText(manifestFile.FullName));
        }

        internal SyncManifest Read(Uri manifestUri)
        {
            return Read(new DownloadService().DownloadString(manifestUri.AbsoluteUri));
        }

        internal  void Write(SyncManifest manifest, FileInfo target)
        {
            var ns = new XmlSerializerNamespaces();
            ns.Add("", "http://syncdeploy.googlecode.com/syncdefinition");


            using (var fs = new FileStream(target.FullName, FileMode.Create))
            {

                _xmlSerializer.Serialize(fs, manifest, ns);
                fs.Close();
            }
        }
    }
}